import {
    getTrackInfo,
    getUuid,
    convetAudiosByAlbum,
    getDeviceOnline,
    getTrackList,
    getAudiosByAlbum,
    sendModeToDevice,
    sleep,
    findCategoryAudioList
} from '../utils';
import { NEXT, COMMON_CATEGORY_ID } from '../config';

/**
 * 获取当前用户播放音频信息
 * @param {当前播放的音频信息} audioId 
 * @param {播放时间} playTime 
 */
export function getCurrentAudio(audioId, playTime) {
    return new Promise((resolve, reject) => {
        getTrackInfo(getUuid(), audioId, (result) => {
            if (result.errcode !== 0 || !result.data || !result.data.name) {
                console.log('获取当前播放的音频信息失败');
                return;
            }
            const audio = result.data;
            const albumId = parseInt(audio.album_id, 10);
            let albumUrl = '';
            if (audio.cover_url) {
                albumUrl = audio.cover_url.middle || '';
            }
            const newAudio = {
                audio_id: audioId,
                duration: audio.duration,
                album_id: albumId,
                album_url: albumUrl,
                name: audio.name
            }
            resolve({ audio: newAudio });
        });
    });
}


/**
 * 获取专辑音频列表
 * @param {当前专辑音频信息} audio 
 */
export function getCurrentAlbumList(audio, upid) {
    return new Promise((resolve, reject) => {
        getTrackList(getUuid(), audio.album_id, 50, upid, (result) => {
            if (result.errcode === 0 && result.data) {
                console.log(result.data)
                console.log("===============");
                const audioList = convetAudiosByAlbum(result.data);
                const newAudio = audioList[0];
                let album_url = newAudio.img_url;
                const newAlbumId = parseInt(newAudio.album_id, 10);
                if (audio && parseInt(audio.album_id, 10) === newAlbumId) {
                    if (audio.album_url) {
                        album_url = audio.album_url;
                    }
                }
                const album = {
                    album_id: newAlbumId,
                    album_url: album_url,
                    name: newAudio.album_name,
                    list: audioList
                };
                resolve({ err: null, album: album });
            }
        })
    })
}

/**
 * 播放列表是否存在该音频
 * @param {当前播放音频} audio 
 * @param {专辑信息} album 
 */
export function existsAudioList(audio, album) {
    let upid = 0;
    const albumId = parseInt(audio.album_id, 10);
    if (album && album.list.length > 0) {
        const audioList = album.list;
        // 属于当前专辑列表
        if (audioList[0].album_id === albumId) {
            for (let index = 0; index < audioList.length; index++) {
                const item = audioList[index];
                if (parseInt(item.audio_id, 10) === parseInt(audio.audio_id, 10)) {
                    console.log(`audio_id:${audio.audio_id}存在播放音频显示列表中，拦截`);
                    return -1;
                }
            }
            // 不包含在列表中,直接获取下一页数据
            upid = audioList[audioList.length - 1].episode || 0;
            console.log(`album_id:${albumId},  upid:${upid}`);
        }
    }
    return upid;
}


/**
 * 处理设备上线数据
 * @param {音频信息} audio 
 * @param {回调函数} cb 
 */
export async function handleDeviceOnine(audio, album, cb) {
    let finalResult = '';
    let audio_id = null;
    let playTime = null;
    for (let index = 0; index < 3; index++) {
        finalResult = await getDeviceOnline(getUuid());
        if (parseInt(finalResult.code, 10) === 0 && audio) {
            const content = JSON.parse(finalResult.data.content).data;
            audio_id = content.audioItemId;
            playTime = content.play_time;
            if (content.audioItemId && parseInt(content.audioItemId, 10) !== audio.audio_id) {
                break;
            }
        }
        await sleep(3000);
    }
    console.log(finalResult);
    if (audio_id) {
        // 减少请求服务器的次数
        const audioItemId = parseInt(audio_id, 10);
        let newAudio = null;
        if (album && album.list) {
            newAudio = album.list.find((item) => {
                return audioItemId === item.audio_id;
            });
        }
        if (newAudio) {
            sessionStorage.setItem('online', 1);
            console.log("当前播放的专辑已经在专辑列表中了");
            if (newAudio.duration) {
                cb({ exists: true, audio: newAudio, playTime: playTime });
            } else {
                const startTime = new Date().getTime();
                const { audio } = await getCurrentAudio(newAudio.audio_id, 0);
                newAudio = Object.assign(newAudio, { duration: audio.duration })
                const finalPlayTime = playTime + (new Date().getTime() - startTime)
                cb({ exists: true, audio: newAudio, playTime: finalPlayTime });
            }
            return;
        }
    }
    cb({ exists: false, data: finalResult });
}



/**
 * 获取当前播放音频信息
 * @param {播放专辑} album 
 * @param {上一次播放音频信息} latestAudio 
 * @param {事件} action 
 * @param {回调} cb 
 */
export async function handleCurrentPlayAudio(categoryId, album, latestAudio, action, cb) {
    const audioList = album.list;
    // 记录上一次播放的音频位置
    const latestIndex = audioList.findIndex(audio => {
        return latestAudio.audio_id === audio.audio_id;
    });

    // 下一首
    if (action === NEXT) {
        if (latestIndex === -1 || latestIndex === audioList.length - 1) {
            if (categoryId > COMMON_CATEGORY_ID) {
                const result = await findCategoryAudioList(categoryId);
                if (result.errcode === 0) {
                    // 仅收藏一首
                    if (result.data.length === 1) {
                        cb({ audio: result.data[0], audioList: result.data });
                        return;
                    }
                    const index = result.data.findIndex(item => {
                        return item.audio_id === latestAudio.audio_id;
                    });
                    console.log(`index:${index}`);
                    if (index >= 0) {
                        cb({ audio: result.data[index + 1], audioList: result.data });
                        return;
                    }
                }
                console.log(`获取类别下的收藏失败`);
            } else {
                const count = album.count || 0;
                const updateAudio = Object.assign(latestAudio, { episode: audioList[audioList.length - 1].episode })
                // console.log(`获取下一页音频数据,album_id:${album.album_id},audio_id:${updateAudio.episode},count:${count}`);
                getAfterAudioList(updateAudio, count, cb);
            }
        } else {
            cb({ audio: audioList[latestIndex + 1] });
        }
        return;
    }
    if (latestIndex === 0) {
        console.log('已经是播放列表中的第一首了');
    } else {
        cb({ audio: audioList[latestIndex - 1] });
    }
}

/**
 * 获取下一页数据
 * @param {上一首播放的音频} latestAudio 
 * @param {回调} cb 
 */
function getAfterAudioList(latestAudio, count, cb) {
    const albumId = latestAudio.album_id;
    // console.log(`episode:${latestAudio.episode},id;${latestAudio.id}`);
    if (latestAudio.episode) {
        getTrackList(getUuid(), albumId, 20, latestAudio.episode, (result) => {
            if (result.errcode === 0 && result.data) {
                const rowAudioList = convetAudiosByAlbum(result.data);
                const index = rowAudioList.findIndex(audio => {
                    return latestAudio.audio_id === audio.audio_id;
                })
                cb({ audio: rowAudioList[index + 1], audioList: rowAudioList });
            }
        })
    } else {
        getAudiosByAlbum(albumId, latestAudio.id, count, (data) => {
            if (data.errcode === 0) {
                const newAudioList = data.data;
                const [first] = newAudioList;
                cb({ audio: first, audioList: newAudioList });
            }
        });
    }
}



// 设备在线状态
export function getOnlineTitle(isOnline, audio) {
    if (isOnline) {
        if (audio) {
            return audio.name;
        }
        return '设备在线';
    }
    return '设备离线';
}
// 电量
export function getBattery(isOnline, battery) {
    if (!isOnline || battery <= 0) {
        return '';
    }
    return `电量:${battery}%`;
}

// 拦截设备在线接口短时间内响应的次数
var interceptOnlineTime = 0;
export function interceptOnline() {
    const start = new Date().getTime();
    if (start - interceptOnlineTime <= 1000) {
        interceptOnlineTime = start;
        return true;
    }
    interceptOnlineTime = start;
    return false;
}

// 接收mqtt拦截
var interceptReceTime = 0;
export function interceptReceive() {
    const start = new Date().getTime();
    if (start - interceptReceTime <= 1000) {
        interceptReceTime = start;
        return;
    }
    interceptReceTime = start;
    return false;
}

var dispatchEventTime = 0;
export function interceptEvent() {
    const start = new Date().getTime();
    if (start - dispatchEventTime <= 600) {
        dispatchEventTime = start;
        return true;
    }
    dispatchEventTime = start;
    return false
}


/**
 * 
 * @param {当前点播的音频id} currentAudioId 
 * @param {*} categoryId 
 */
export async function notifyDeviceMode(currentAudioId, categoryId) {
    try {
        for (let index = 0; index < 2; index++) {
            const result = await sendModeToDevice(currentAudioId, categoryId);
            if (result.errcode === 0 && result.data.data) {
                const relData = result.data.data.content;
                if (relData && JSON.parse(relData).errcode === 0) {
                    break;
                }
            }
            await sleep(5000);
        }
    } catch (error) {
        console.log(error);
    }
}

/**
 * 查找类别信息
 * @param {类别}}} categoryId 
 */
export function findCategory(categoryId) {
    const storeList = JSON.parse(localStorage.getItem('store_list'));
    return storeList.find(item => {
        return parseInt(item.category_id, 10) === categoryId;
    })
}
